package com.cvmars.jianyou.module.activity;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.model.CollapsingToolbarLayoutState;
import com.cvmars.jianyou.model.ImageModel;
import com.cvmars.jianyou.module.adapter.FindAdapter;
import com.cvmars.jianyou.module.base.BaseActivity;
import com.cvmars.jianyou.module.base.BasePictureActivity;
import com.cvmars.jianyou.module.model.EventFindRefresh;
import com.cvmars.jianyou.module.model.FindListModel;
import com.cvmars.jianyou.module.model.FindModel;
import com.cvmars.jianyou.module.model.TopicModel;
import com.cvmars.jianyou.ui.pulltorefresh.PulltoRefreshRecyclerView;
import com.cvmars.jianyou.utils.LogUtils;
import com.cvmars.jianyou.utils.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import jp.wasabeef.glide.transformations.BlurTransformation;

public class FindTopicActivity extends BasePictureActivity {

    @BindView(R.id.find_disc_img)
    ImageView findDiscImg;
    @BindView(R.id.txt_desc_title)
    TextView txtDescTitle;
    @BindView(R.id.txt_desc_desc)
    TextView txtDescDesc;
    @BindView(R.id.find_desc_detail)
    TextView findDescDetail;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.list_find)
    PulltoRefreshRecyclerView listHome;
    @BindView(R.id.empty_view)
    TextView emptyView;
    @BindView(R.id.find_add)
    TextView findAdd;


    FindAdapter homeAdapter;

    boolean isHot;

    List<FindModel> modelList = new ArrayList<>();
    TopicModel model;
    @BindView(R.id.find_chat)
    Button findChat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_topic);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);
        homeAdapter = new FindAdapter(this, R.layout.item_find, modelList);
        model = (TopicModel) getIntent().getSerializableExtra("model");

        if (model != null) {

            txtDescTitle.setText("#" + model.name + "#");
            txtDescDesc.setText(model.desc);
            Glide.with(this).load(model.logo_url)
                    .bitmapTransform(new BlurTransformation(this, 6))
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(findDiscImg);

        }
        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(FindTopicActivity.this, FindDetailActivity.class);
                intent.putExtra("data", modelList.get(position));
                startActivity(intent);

//                ActivityOptions options = null;
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                    options = ActivityOptions.makeSceneTransitionAnimation(FindTopicActivity.this, view,
//                            "iv");
//                    startActivity(intent, options.toBundle());
//                } else {
//                    startActivity(intent);
//                }
            }
        });

        homeAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout._loading_layout_empty,null));
        listHome.setAdapter(homeAdapter);

        listHome.setEnableRefresh(false);
        listHome.setPullRefreshListener(new PulltoRefreshRecyclerView.RecyPtrHandler() {
            @Override
            public void onLoadMore() {

                requestNew();
            }

            @Override
            public void onRefresh() {

                listHome.mCurPager = 1;
                requestNew();


            }
        });

        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                        toolbarTitle.setVisibility(View.GONE);//设置title为EXPANDED
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        toolbarTitle.setVisibility(View.VISIBLE);
                        state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    }
                } else {
                    if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                        state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                    }
                }
            }
        });


        EventBus.getDefault().register(this);
        requestNew();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventRefresh(EventFindRefresh refresh) {

        if (refresh.isRefresh) {

            listHome.mCurPager = 1;
            requestNew();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    CollapsingToolbarLayoutState state;

    private void requestNew() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getTopicFindList(model.id,
                listHome.mCurPager)
                , new SimpleSubscriber<HttpResult<FindListModel>>() {
                    @Override
                    protected void _onNext(HttpResult<FindListModel> o) {

                        getLoadDialogAndDismiss();

                        FindListModel data = o.getData();

                        if (data != null) {

                            List<FindModel> results = data.results;

                            if (results != null) {

                                if (listHome.mCurPager == 1) {
                                    modelList.clear();
                                }
                                modelList.addAll(results);
                                homeAdapter.notifyDataSetChanged();
                                listHome.refreshComplete();
                                listHome.loadMoreComplete();

                            }
                            if (data.next == null) {
                                listHome.loadMoreEnd();
                            }
                        }
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });

    }


    public void onFind(View view) {


        selectMultPic();


//        Bundle bundle = new Bundle();
//        bundle.putString("topic", "#" + model.name + "#");
//        goActivity(bundle, FindAddWeiboActivity.class);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);

                    ArrayList<ImageModel> list = new ArrayList<>();
                    if (localMedias != null && localMedias.size() > 0) {


                        for (int i = 0; i < localMedias.size(); i++) {

                            ImageModel model = new ImageModel();
                            model.imgPath = (localMedias.get(i).getCompressPath());
                            model.w = localMedias.get(i).getWidth();
                            model.h = localMedias.get(i).getHeight();
                            list.add(model);
                        }
                    }

                    Intent intent = new Intent(this, FindAddWeiboActivity.class);
                    intent.putExtra("list", list);
                    intent.putExtra("topic", "#" + model.name + "#");
                    LogUtils.d("list :" + list.toString());
                    startActivity(intent);
                    break;
            }
        }
    }


    @OnClick(R.id.find_chat)
    public void onViewClicked() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getGroup(model.id)
                , new SimpleSubscriber<HttpResult<Object>>() {
                    @Override
                    protected void _onNext(HttpResult<Object> o) {

                        RongIM.getInstance().startGroupChat(FindTopicActivity.this, model.id, model.name);
                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });


    }



}
